var editRowsNumber,_datasDatagrid, selectForm;
var formAddRow,dialogAddRow,sessionID,userIds,id,groupId,content,checkStatus,name,timing,checkName,createDate1,createDate2,isTime;

/*推送*/
function push(o) {
	if (o) {
		_datasDatagrid.datagrid('selectRow', o);
	}
	pushHandler();
}

function pushHandler() {
		id.val(0);
		groupId.combobox('setValue','');
		timing.datetimebox('disable');
		content.html('');
		content.readonly(false);
		$('#name').val('系统消息');
		dialogAddRow.dialog({title:'消息推送',iconCls:'icon-add',buttons:[{text:'推送',handler:dialogEnterHandler}]});
		dialogAddRow.dialog('open');
}

/*定时推送*/
function timePush(o) {
	if (o) {
		_datasDatagrid.datagrid('selectRow', o);
	}
	timePushHandler();
}

function timePushHandler() {
		id.val(0);
		timing.datetimebox('enable');
		groupId.combobox('setValue','');
		timing.datetimebox('setValue','');
		content.html('');
		$('#name').val('系统消息');
		dialogAddRow.dialog({title:'消息定时推送',iconCls:'icon-add',buttons:[{text:'推送',handler:dialogEnterHandler}]});
		dialogAddRow.dialog('open');
}
/*启动任务*/
function startPush(o){
	if (o) {
		_datasDatagrid.datagrid('selectRow', o);
	}
	startPushHandler();
}

/*启动任务*/
function startPushHandler() {
	var rows = _datasDatagrid.datagrid('getSelections');
	if (rows.length > 0) {
		$.messager.confirm('请确认', '您确实要启动当前所有选择的任务吗？', function(b){
			if (b) {
				var ids = [];
				for ( var i = 0; i < rows.length; i++) {
					status = rows[i].status;
					if(status != 0){
						$.messager.alert('提示', '启动的任务包含已完成任务,请重新选择!', 'error');
						return ;
					}
					var time = rows[i].timing;
					time = time.replace(/-/g,"/");
					var date = new Date(time);
					if(date <= new Date()){
						$.messager.alert('提示', '当前启动任务已完成,请重新选择!', 'error');
						return ;
					}
					ids.push(rows[i].id);
				}
				$.post(sy.bp()+"/admin/messageSpread/timing", {ids:ids.join(",")}, function(data) {
					if (data && data.result==1) {
						$.messager.show({msg:data.msg,title:'系统提示'});
						editRowsNumber = -1;
						_datasDatagrid.datagrid('unselectAll');
						_datasDatagrid.datagrid('reload');
					} else {
						$.messager.alert('警告', data.msg, 'warning');
					}
				}, "json");
			}
		});
	} else {
		$.messager.alert('提示', '请选择要启动的任务', 'error');
	}
};

/*Datagrid删除行*/
function deleteRow() {
	var rows = _datasDatagrid.datagrid('getSelections');
	if (rows.length > 0) {
		$.messager.confirm('请确认', '您确实要删除当前所有选择的记录并删除所有用户消息吗？', function(b){
			if (b) {
				var ids = [];
				for ( var i = 0; i < rows.length; i++) {
					ids.push(rows[i].id);
				}
				$.post(sy.bp()+"/admin/messageSpread/delete", {ids:ids.join(",")}, function(data) {
					if (data && data.result==1) {
						$.messager.show({msg:data.msg,title:'系统提示'});
						editRowsNumber = -1;
						_datasDatagrid.datagrid('unselectAll');
						_datasDatagrid.datagrid('reload');
					} else {
						$.messager.alert('警告', data.msg, 'warning');
					}
				}, "json");
			}
		});
	} else {
		$.messager.alert('提示', '请选择要删除的记录', 'error');
	}
};

function updateRow(o) {
	if (o) {
		_datasDatagrid.datagrid('selectRecord', o);
	}
	updateRowHandler();
}
function clearNow(){
	$.messager.confirm('请确认', '您确实要立即清理系统中无效的图片吗？', function(b){
		if (b) {
		/*	var ids = [];
			for ( var i = 0; i < rows.length; i++) {
				ids.push(rows[i].id);
			}*/
			var ids=0;
			var actionTime="2015/09/01";
			$.post(sy.bp()+"/admin/pic/delete", {id:ids,times:actionTime}, function(data) {
				if (data && data.result>=0) {
					$.messager.show({msg:data.msg,title:'系统提示'});
					/*editRowsNumber = -1;*/
					_datasDatagrid.datagrid('unselectAll');
					_datasDatagrid.datagrid('reload');
				} else {
					$.messager.alert('警告', data.msg, 'warning');
				}
			}, "json");
		}
	});
}
/*Datagridge更新行*/
function updateRowHandler() {
	var row = _datasDatagrid.datagrid('getSelections');
	switch (row.length) {
	case 0:
		$.messager.alert('提示', '请选择要修改的记录', 'warning');
		break;
	case 1:
		$('#name').val(row[0].name);
		timing.datetimebox('setValue',row[0].timing);
		groupId.combobox('setValue',row[0].groupId);
		content.html(row[0].content);
		groupId.attr('readonly',true);
		content.readonly(true);
		$('#name').attr('readonly',true);
		dialogAddRow.dialog({title:'消息推送',iconCls:'icon-add'});
		dialogAddRow.dialog('open');
		break;
	default:
		$.messager.alert('提示', '您选择了多条记录数，请每次修改一条记录', 'warning');
		break;
	}
}

/*Datagrid保存行数据*/
function saveRow() {
	_datasDatagrid.datagrid('endEdit', editRowsNumber);
};

/*Datagrid取消编辑*/
function rejectRow() {
	editRowsNumber = -1;
	_datasDatagrid.datagrid('rejectChanges');
	_datasDatagrid.datagrid('unselectAll');
};

/*查询面板查询按钮方法*/
function search_datas() {
	_datasDatagrid.datagrid('load',sy.serializeObject(selectForm));
}

/*查询面板清空按钮方法*/
function reset_datas() {
	checkName.combobox('setValue','');
	isTime.combobox('setValue',-1);
	checkStatus.combobox('setValue',-1);
	createDate1.datetimebox('setValue','');
	createDate2.datetimebox('setValue','');
	_datasDatagrid.datagrid('load',{});
}

function dialogEnterHandler() {
	if (formAddRow.form('validate')) {
		content.sync();
		var url = sy.bp() + '/admin/messageSpread/';
		if (id.val() == 0) {
			url += 'add';
		} else {
			url += 'update';
		}
		$.post(url, $('#formAddRow').serialize(), function(data){
			if(data && data.result ==1) {
				dialogAddRow.dialog('close');
				$.messager.show({title:'系统提示', msg:data.msg, timingout:2000, showType:'slide'});
				_datasDatagrid.datagrid('reload');
				editRowsNumber = -1;
			} else {
				$.messager.alert('错误提示', data.msg);
			}
		},"json");
	}
}

$(function() {
	editRowsNumber = -1;
	_datasDatagrid = $('#_datasDatagrid');
	selectForm = $('#selectForm');
	dialogAddRow = $('#dialogAddRow');
	content = $('#content');
	name = $('#name').validatebox({required: true});
	timing = $('#timing').datetimebox({ 
		showSeconds: true 
	});
	checkName = $('#checkName').combobox({   
        url:sy.bp()+'/admin/group/listGroup',   
        editable:false, 
        cache: false,  
        panelHeight: '150',  
        valueField:'id',     
        textField:'name', 
	});;
	createDate1 = $('#createDate1').datetimebox({editable:false,showSeconds: true }).datetimebox('activeTextArrow');
	createDate2 = $('#createDate2').datetimebox({editable:false,showSeconds: true }).datetimebox('activeTextArrow');
	isTime = $('#isTime').combobox({valueField:'code',textField:'name',editable:false,
		url:sy.bp() + "/admin/dictionary/listDictionary?name=定时任务"
	}).combobox('activeTextArrow');
    checkStatus = $('#checkStatus').combobox({valueField:'code',textField:'name',editable:false,
		url:sy.bp() + "/admin/dictionary/listDictionary?name=任务发送状态"
	}).combobox('activeTextArrow');
	groupId = $('#groupId').combobox({   
        url:sy.bp()+'/admin/group/listGroup',   
        editable:false, 
        cache: false,  
        panelHeight: '150',  
        valueField:'id',     
        textField:'name', 
	    onHidePanel: function(){
	      $("#userIds").combobox("setValue",'');
	      var id = $('#groupId').combobox('getValue');
	      console.info(id);
	      $.ajax({  
		      type: "POST",  
		      url: sy.bp()+'/admin/user/listGroupUser/'+id,  
		      cache: false,  
		      dataType : "json",  
		      success: function(data){  
		    	  $("#userIds").combobox("loadData",data);  
		      }  
	       });       
	   }  
	});
	userIds = $('#userIds').combobox({   
        editable:false,
        cache: false,  
        panelHeight: '150',
        valueField:'id',     
        textField:'username'
      });
	formAddRow = $('#formAddRow');
	id = $('#id');
	sessionID = $('#sessionID').val();
	status = $('#status').combobox({valueField:'code',textField:'name',editable:false,
		url:sy.bp() + "/admin/dictionary/listDictionary?name=启用状态"
	}).combobox('activeTextArrow');
	
	dialogAddRow.show().dialog({resizable:false,closed:true,closable:true,modal:true});
	
	_datasDatagrid.datagrid({
		url : sy.bp()+'/admin/pic/list',
		fit : true,
		autoRowHeight : true,
		striped : true,
		rownumbers : true,
		pagination : true,
		singleSelect : false,
		fitColumns : true,
		pageSize : 10,
		pageList : [10,20,30,40,50],
		nowrap : true,
		border : false,
		idField : 'id',
		sortName : 'id',
		sortOrder : 'desc',
		view: sy.myview,
        emptyMsg: '没有查询到相关数据',
		toolbar: [
		          {text:'推送',iconCls: 'icon-chart_bar_add',handler: pushHandler},'-',
		          {text:'定时推送',iconCls: 'icon-chart_bar_add',handler: timePushHandler},'-',
		          {text:'立即清理',iconCls: 'icon-delete',handler: clearNow},'-',
		          {text:'保存',iconCls: 'icon-save',handler: saveRow},'-',
		          {text:'撤销',iconCls: 'icon-redo',handler: rejectRow},'-',
		          {text:'刷新',iconCls: 'icon-reload',handler: function(){_datasDatagrid.datagrid('reload');}},'-',
				  ],
		frozenColumns: [[	
		                 	{field:'id',title:'编号',align:'center',width:100,checkbox:true},
						]],
			   columns:[[
		          		 {field:'name',title:'消息名',align:'left',width:100,sortable:true},
		          		 {field:'groupName',title:'推送组名',align:'left',width:100,sortable:true},
		          		 {field:'groupId',title:'推送组Id',align:'left',width:100,sortable:true,hidden:true},
		          		 {field:'content',title:'消息内容',align:'left',width:200,sortable:true},
		          		 {field:'createName',title:'创建用户',align:'left',width:100,sortable:true},
						 {field:'createTime',title:'创建时间',align:'left',width:100,sortable:true},
						 {field:'timing',title:'发送时间',align:'left',width:100,sortable:true},
						 {field:'isTime',title:'定时推送',align:'left',width:50,sortable:true,formatter:function(value,row,index){
							 if (value){
								 return '<span style="color:green;">是</span>';
							 } else {
									return '<span style="color:#8F8F8F;">否</span>';
							 }
						  }},
						 {field:'status',title:'发送状态',align:'left',width:80,sortable:true,formatter:function(value,row,index){
							   if (value){
									return '<span style="color:green;">成功</span>';
								} else {
									return '<span style="color:red;">未完成</span>';
								}
						 }},
						 {field:'action1',title:'启动推送',align:'center',width:60,sortable:true,formatter:function(value,row,index){
							    var str = '';
								var time = row.timing;
								var bo = dateCompare(time);
							    if(row.status == 0 && row.isTime == 1 && bo){
								  str += $.formatString('<a href="javascript:void(0)" class="action1" onclick="startPush(\'{0}\')"></a>',index) ;
							    }
							   return str;
						 }},
				]],
		onLoadSuccess : function(data) {
			editRowsNumber = -1;
			$('.action1').linkbutton({plain:true,iconCls:'icon-control_play_blue'});  
			$.messager.progress('close');
		},
		onDblClickRow : function(rowIndex, rowData) {
			if (editRowsNumber != -1) {
				_datasDatagrid.datagrid('endEdit', editRowsNumber);
			} else {
				updateRow(rowData.id);
			}
		},
		onRowContextMenu : function(e, rowIndex, rowData){
			e.preventDefault();	
			_datasDatagrid.datagrid('unselectAll').datagrid('selectRow', rowIndex);
			$('#datagridContextMenu').menu('show', {left:e.pageX,top:e.pageY });
		},
		onAfterEdit : function(rowIndex, rowData, changes) { 
			var inserted = _datasDatagrid.datagrid('getChanges', 'inserted');
			var updated = _datasDatagrid.datagrid('getChanges', 'updated');
			if (inserted.length < 1 && updated.length < 1) {
				editRowsNumber = -1;
				_datasDatagrid.datagrid('unselectAll');
				return;
			}
			var url='';
			if (inserted.length > 0) {
				url=sy.bp()+'/admin/messageSpread/add';
			}
			if (updated.length > 0) {
				url=sy.bp()+'/admin/messageSpread/update';
			}
			rowData.teacherId = ctInfo.teacherData.id;
			rowData.cid = ctInfo.courseData.id;
			rowData.teacherName = ctInfo.teacherData.name;
			rowData.courseName = ctInfo.courseData.name;
			$.post(url, rowData, function(data) {
				if (data && data.result==1) {
					_datasDatagrid.datagrid('acceptChanges');
					$.messager.show({msg:data.msg,title:'系统提示'});
					_datasDatagrid.datagrid('reload');
				} else {
					_datasDatagrid.datagrid('rejectChanges');
					$.messager.alert('错误', data.msg, 'warning');
				}
				editRowsNumber = -1;
				_datasDatagrid.datagrid('unselectAll');
			}, "json");
		}
	});
	
	$(document).keydown(function(event){
		if(event.keyCode==13){
			search_datas();
		} 
	});
});

function dateFormat(s){
    if (!s) return new Date();
    var y = s.substring(0,4);
    var m =s.substring(5,7);
    var d = s.substring(8,10);
    var h = s.substring(11,13);
    var min = s.substring(14,16);
    var sec = s.substring(17,19);
    if (!isNaN(y) && !isNaN(m) && !isNaN(d) && !isNaN(h) && !isNaN(min) && !isNaN(sec)){
      return new Date(y,m-1,d,h,min,sec);
    } else {
      return new Date();
    }
  }
function dateCompare(time){
	time = dateFormat(time);
	var current = new Date();
	var message = new Date(time);
	if(current > message){
		return true;
	}
	return false;
}

KindEditor.ready(function(K) {
	content = K.create('textarea[name="content"]', {
		width : '600px',
		minWidth : '600px',
		resizeType : 0,
		allowPreviewEmoticons : false,
		allowImageUpload : false,
		items : [
			'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
			'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
			'insertunorderedlist', '|', 'emoticons', 'image', 'link'],
		autoHeightMode : true,
		afterCreate : function() {
			this.loadPlugin('autoheight');
		}
	});
});